﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Shimpossible.Vonage
{
    [global::System.AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
    sealed class VonageSchemaAttribute : Attribute
    {
        readonly string schema;

        // This is a positional argument
        public VonageSchemaAttribute(string schema)
        {
            this.schema = schema;

            // TODO: Implement code here
            throw new NotImplementedException();
        }

        public string Schema
        {
            get { return schema; }
        }
    }

    /// <summary>
    /// Get the correct VonnageConnect based on a url
    /// 
    /// </summary>
    /// <example>
    /// VonageConnectionFactory f = new VonageConnectionFactory();
    /// VonnageConnection c = f.GetConnection("https://secure.vonage.com")
    /// c.Open(user,pass);
    /// </example>
    public class VonageConnectionFactory
    {
        Dictionary<string, Type> types = new Dictionary<string, Type>();

        public VonageConnectionFactory()
        {

        }

        private void FindConnectionTypes(Assembly asm)
        {
            foreach (Type t in asm.GetTypes())
            {
                if (!typeof(VonageConnection).IsAssignableFrom(t) || 
                    t == typeof(VonageConnection))
                {
                    foreach (object o in t.GetCustomAttributes(false))
                    {
                        if (o is VonageSchemaAttribute)
                        {
                            VonageSchemaAttribute s = o as VonageSchemaAttribute;
                            types[s.Schema] = t;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// retrieve the correct Connect for the given url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public VonageConnection GetConnection(Uri url)
        {
            Type t;
            if (types.TryGetValue(url.Scheme, out t))
            {
                object[] args = new object[]{
                    url.ToString()
                };
                return (VonageConnection)Activator.CreateInstance(t, url.Scheme, args);
            }
            else
            {
                throw new InvalidOperationException("Unknown schema for url " + url);
            }
        }
    }
}
